package com.hh.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hh.entity.UserAddr;
import com.hh.service.UserAddrService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户配送地址 前端控制器
 * </p>
 *
 * @author 辉辉
 * @since 2022-08-19
 */
@RestController
@RequestMapping("/p/address")
@Api(tags = "用户收货地址查询")
public class UserAddrController {

    @Resource
    private UserAddrService userAddrService;

    @GetMapping("/list")
    @ApiOperation("全查询用户的收货地址")
    public ResponseEntity<List<UserAddr>> loadAllUserAddr() {
        // 拿到当前用户信息
        String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        List<UserAddr> userAddrs = userAddrService.findUserAddr(openId);
        return ResponseEntity.ok(userAddrs);
    }

    @PostMapping("/addAddr")
    @ApiOperation("新增收货地址")
    public ResponseEntity<Void> addUserAddr(@RequestBody UserAddr userAddr) {
        String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userAddr.setUserId(openId);
        userAddrService.save(userAddr);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/defaultAddr/{id}")
    @ApiOperation("修改用户的默认地址")
    public ResponseEntity<Void> changeDefaultAddr(@PathVariable("id") Long id) {
        String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userAddrService.changeUserDefaultAddr(openId, id);
        return ResponseEntity.ok().build();
    }

    // ----------远程调用--------

    /**
     * 获取默认用户收货地址
     *
     * @param openId
     * @return
     */
    @GetMapping("/getDefaultAddress")
    @ApiOperation("获取默认用户收货地址")
    UserAddr getDefaultAddress(@RequestParam("openId") String openId) {
        return userAddrService.getOne(Wrappers.<UserAddr>lambdaQuery()
                .eq(UserAddr::getUserId, openId)
                .eq(UserAddr::getCommonAddr, 1)
        );
    }
}

